# -*- coding: utf-8 -*-
# @Time : 2021/9/4 14:22
# @Author : 唐宁
# @Site :  签名校验类
# @File : Signature.py
# @Software: PyCharm
import time
import hashlib
from fastapi import Header
from config.Setting import settings
from exception.ErrorCodeEnum import ErrorCodeEnum
from exception.ErrorCodeException import ErrorCodeException


async def validator_signature(timestamp, sign: str = Header(...)):
    # 必传参数
    if timestamp is None or sign is None:
        raise ErrorCodeException(ErrorCodeEnum.SIGN_ERROR)
    # 时间校验
    now = time.time()
    if (now - float(timestamp)) > settings.EXPIRE_TIME:
        raise ErrorCodeException(ErrorCodeEnum.SIGN_ERROR)
    # 拼接字符串
    secret = settings.SECRET_KEY + str(timestamp)
    # md5 加密
    result = hashlib.md5(secret.encode(encoding='UTF-8')).hexdigest()
    # 对比加密结果
    if result != sign:
        raise ErrorCodeException(ErrorCodeEnum.SIGN_ERROR)
